package com.example.yjhero.safeapp.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import com.example.yjhero.safeapp.entities.ContactInfo;
import java.util.ArrayList;
import java.util.List;
import static com.example.yjhero.safeapp.utils.LogUtil.logI;

public class ContactInfoParser {
    /**
     * 获取本地联系人
     */
    public static List<ContactInfo> getSystemContact(Context context) {
        List<ContactInfo> cList = new ArrayList<>();
        // 号码
        String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
        // 联系人姓名
        String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
        // 本机联系人(非sim)
        Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(phoneUri, new String[]{NUM, NAME}, null, null, null);
        while (cursor.moveToNext()) {
            ContactInfo contact = new ContactInfo(cursor.getString(cursor.getColumnIndex(NAME)),
                    cursor.getString(cursor.getColumnIndex(NUM)));
            logI("ExampleInstrumentedTest", "getContactInfo |  ", "" + contact);
            cList.add(contact);
        }
        cursor.close();
        return cList;
    }

    /**
     * 获取SIM卡联系人
     */
    public static List<ContactInfo> getSimContacts(Context context) {
        List<ContactInfo> cList = new ArrayList<>();
        String adn = "content://icc/adn";
//        String adn = "content://sim/adn";
        // 读取SIM卡手机号,有两种可能:content://icc/adn与content://sim/adn
        Cursor cursor = null;
        try {

            Intent intent = new Intent();
            intent.setData(Uri.parse(adn));
            Uri uri = intent.getData();
            logI("ExampleInstrumentedTest", "getSimContact |  ", uri + "");
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 取得联系人名字
                    int nameIndex = cursor.getColumnIndex("name");
                    // 取得电话号码
                    int numberIndex = cursor.getColumnIndex("number");
                    String number = cursor.getString(numberIndex);
                    String name = cursor.getString(nameIndex);
                    ContactInfo contact = new ContactInfo(name, number);
                    cList.add(contact);
                    logI("ExampleInstrumentedTest", "getSimContact |  ", "" + numberIndex + "");
                }
                cursor.close();
            }
        } catch (Exception e) {
            logI("ExampleInstrumentedTest", "getSimContact |  ", "" + e);
            if (cursor != null)
                cursor.close();
        }
        return cList;
    }
}
